package com.movitech.mobile.cz.base.bizconfig.service.impl;

import com.movitech.mobile.cz.base.bizconfig.entity.SStrategicPartners;
import com.movitech.mobile.cz.base.bizconfig.entity.ext.ExtSStrategicPartners;
import com.movitech.mobile.cz.base.bizconfig.mapper.SStrategicPartnersMapper;
import com.movitech.mobile.cz.base.bizconfig.mapper.ext.ExtSStrategicPartnersMapper;
import com.movitech.mobile.cz.base.bizconfig.service.SStrategicPartnersService;
import com.movitech.mobile.cz.base.common.license.LicenseUtil;
import com.movitech.mobile.cz.base.common.util.CommonConstants;
import com.movitech.mobile.cz.base.common.util.IdGenUtils;
import com.movitech.mobile.cz.base.common.util.ListObjCopyUtil;
import com.movitech.mobile.cz.base.common.util.PageCode;
import com.movitech.mobile.cz.base.common.utils.StringUtils;
import com.movitech.mobile.cz.base.modules.config.AttachmentSubTypeEnum;
import com.movitech.mobile.cz.base.modules.config.AttachmentTypeEnum;
import com.movitech.mobile.cz.base.modules.controller.RestReturnResult;
import com.movitech.mobile.cz.base.modules.vo.PageRequestVO;
import com.movitech.mobile.cz.base.sys.bizvo.AttachmentVO;
import com.movitech.mobile.cz.base.sys.bizvo.BannerListResponseVO;
import com.movitech.mobile.cz.base.sys.bizvo.StrategicPartnersListResponseVO;
import com.movitech.mobile.cz.base.sys.bizvo.StrategicPartnersRequestVO;
import com.movitech.mobile.cz.base.sys.entity.SAttachment;
import com.movitech.mobile.cz.base.sys.service.SAttachmentService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.movitech.mobile.cz.base.util.UserUtils;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 战略合作伙伴 服务实现类
 * </p>
 *
 * @author Movitech Mobile
 * @since 2018-02-28
 */
@Service("sStrategicPartnersService")
@Transactional
public class SStrategicPartnersServiceImpl extends ServiceImpl<SStrategicPartnersMapper, SStrategicPartners> implements SStrategicPartnersService {


	private final static Logger logger = Logger.getLogger(SStrategicPartnersServiceImpl.class);

	@Autowired
	private SAttachmentService sAttachmentService;

	@Autowired
	private ExtSStrategicPartnersMapper extSStrategicPartnersMapper;

	@Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
	@Override
	public RestReturnResult<Object> saveOrUpdateStrategicPartners(StrategicPartnersRequestVO strategicPartnersRequestVO) throws RuntimeException {
		RestReturnResult<Object> hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[0], CommonConstants.ERROR_DESCS[0]);

		try{
			LicenseUtil.INSTANCE.validate();
			SStrategicPartners strategicPartners = null;
			if(strategicPartnersRequestVO != null){

				if(StringUtils.isNotEmpty(strategicPartnersRequestVO.getId())){ //update

					strategicPartners = baseMapper.selectById(strategicPartnersRequestVO.getId());
					if(strategicPartners != null){

						strategicPartners.setPartnerName(strategicPartnersRequestVO.getPartnerName());
						strategicPartners.setPartnerSort(strategicPartnersRequestVO.getPartnerSort());

						Date updateDate = new Date();
						String userId = UserUtils.getCurrentUserId();
						strategicPartners.setUpdateBy(userId);
						strategicPartners.setUpdateDate(updateDate);
						strategicPartners.setDelFlag(CommonConstants.NO_INTEGER);

						baseMapper.updateById(strategicPartners);

						//上传图片
						sAttachmentService.deleteBatch(strategicPartners.getId(), AttachmentTypeEnum.ATTACHMENT_TYPE_35.getCode(),0);

						List<AttachmentVO> lstAttachments = strategicPartnersRequestVO.getLstAttachments();
						this.saveStrategicPartnerPics(lstAttachments, strategicPartners.getId());

						hResult = new RestReturnResult<Object>(CommonConstants.SUCCESS, CommonConstants.SUCCESS_CODES[1], CommonConstants.SUCCESS_DESCS[1]);

					}else{ //数据不存在
						hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[2], CommonConstants.ERROR_DESCS[2]);
					}

				}else{ //insert

					strategicPartners = new SStrategicPartners();
					strategicPartners.setPartnerName(strategicPartnersRequestVO.getPartnerName());
					strategicPartners.setPartnerSort(strategicPartnersRequestVO.getPartnerSort());

					Date createDate = new Date();
					String userId = UserUtils.getCurrentUserId();
					strategicPartners.setId(IdGenUtils.uuid());
					strategicPartners.setPartnerStatus(CommonConstants.YES_INTEGER);
					strategicPartners.setCreateBy(userId);
					strategicPartners.setCreateDate(createDate);
					strategicPartners.setUpdateBy(userId);
					strategicPartners.setUpdateDate(createDate);
					strategicPartners.setDelFlag(CommonConstants.NO_INTEGER);

					baseMapper.insert(strategicPartners);

					//上传图片
					List<AttachmentVO> lstAttachments = strategicPartnersRequestVO.getLstAttachments();
					this.saveStrategicPartnerPics(lstAttachments, strategicPartners.getId());

					hResult = new RestReturnResult<Object>(CommonConstants.SUCCESS, CommonConstants.SUCCESS_CODES[0], CommonConstants.SUCCESS_DESCS[0]);
				}

			}else{//请求数据出错
				hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[3], CommonConstants.ERROR_DESCS[3]);
			}
		}catch(Exception e){
			e.printStackTrace();
			logger.error("============saveOrUpdateStrategicPartners=========e:=====" + e.getMessage());
			throw new RuntimeException(e.getMessage(), e.getCause());
		}

		return hResult;
	}

	private boolean saveStrategicPartnerPics(List<AttachmentVO> lstAttachments, String strategicPartnerId) throws Exception{

		boolean flag = false;

		if(lstAttachments != null && lstAttachments.size() > 0){
			List<SAttachment>  attachments = ListObjCopyUtil.copyTo(lstAttachments, SAttachment.class);

			for(SAttachment sa : attachments){
				sa.setRelatedId(strategicPartnerId);
				sa.setAttachmentType(AttachmentTypeEnum.ATTACHMENT_TYPE_35.getCode());
				sa.setAttachmentSubType(AttachmentSubTypeEnum.ATTACHMENTSUBTYPE_2.getCode());
				sa.setBaseFeilds(UserUtils.getCurrentUserId(), null, CommonConstants.NO_INTEGER, true);
			}

			if(attachments != null && attachments.size() > 0){
				flag = sAttachmentService.insertBatch(attachments);
			}

			LicenseUtil.INSTANCE.validate();
		}

		return flag;

	}

	@Override
	public RestReturnResult<Object> updateStrategicPartnersForDel(String id) {
		RestReturnResult<Object> hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[0], CommonConstants.ERROR_DESCS[0]);

		if(StringUtils.isNotEmpty(id)){

			SStrategicPartners strategicPartners = baseMapper.selectById(id);
			if(strategicPartners != null){
				strategicPartners.setDelFlag(CommonConstants.YES_INTEGER);

				Date updateDate = new Date();
				String userId = UserUtils.getCurrentUserId();
				strategicPartners.setUpdateBy(userId);
				strategicPartners.setUpdateDate(updateDate);

				baseMapper.updateById(strategicPartners);

				hResult = new RestReturnResult<Object>(CommonConstants.SUCCESS, CommonConstants.SUCCESS_CODES[2], CommonConstants.SUCCESS_DESCS[2]);

			}else{ //数据不存在
				hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[2], CommonConstants.ERROR_DESCS[2]);
			}

		}else{
			hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[3], CommonConstants.ERROR_DESCS[3]);
		}

		LicenseUtil.INSTANCE.validate();
		return hResult;
	}

	@Override
	public RestReturnResult<Object> updateStrategicPartnersStatus(StrategicPartnersRequestVO strategicPartnersRequestVO) {
		RestReturnResult<Object> hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[0], CommonConstants.ERROR_DESCS[0]);

		if(strategicPartnersRequestVO != null){

			if(StringUtils.isNotEmpty(strategicPartnersRequestVO.getId())){

				SStrategicPartners strategicPartners = baseMapper.selectById(strategicPartnersRequestVO.getId());

				if(strategicPartners != null){
					strategicPartners.setPartnerStatus(strategicPartnersRequestVO.getPartnerStatus());

					Date updateDate = new Date();
					String userId = UserUtils.getCurrentUserId();
					strategicPartners.setUpdateBy(userId);
					strategicPartners.setUpdateDate(updateDate);

					baseMapper.updateById(strategicPartners);

					if(CommonConstants.YES_INTEGER == strategicPartners.getPartnerStatus()){//启用
						hResult = new RestReturnResult<Object>(CommonConstants.SUCCESS, CommonConstants.SUCCESS_CODES[3], CommonConstants.SUCCESS_DESCS[3]);
					}else{//停用
						hResult = new RestReturnResult<Object>(CommonConstants.SUCCESS, CommonConstants.SUCCESS_CODES[4], CommonConstants.SUCCESS_DESCS[4]);
					}

				}else{ //数据不存在
					hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[2], CommonConstants.ERROR_DESCS[2]);
				}

			}else{
				hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[3], CommonConstants.ERROR_DESCS[3]);
			}

		}else{//请求数据出错
			hResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[3], CommonConstants.ERROR_DESCS[3]);
		}

		LicenseUtil.INSTANCE.validate();
		return hResult;
	}

	@Override
	public RestReturnResult<Object> getStrategicPartnersList(PageRequestVO pageRequestVO) {
		RestReturnResult<Object> hResult = new RestReturnResult<Object>(CommonConstants.FAIL);

		try{

			PageCode pageCode = new PageCode(pageRequestVO.getPageNumber(), pageRequestVO.getPageSize());

			Map<String, Object> map = new HashMap<String, Object>();
			pageCode.setCount(extSStrategicPartnersMapper.getStrategicPartnersListCounts(map));

			map.put("currentRecordNum", (pageCode.getPageNo() - 1) * pageCode.getPageSize());
            map.put("pageSize", pageCode.getPageSize());
            map.put("isPage", pageRequestVO.getPageFlag());

            List<ExtSStrategicPartners> ls = extSStrategicPartnersMapper.getStrategicPartnersList(map);
            if(ls != null && ls.size() > 0){
            	List<StrategicPartnersListResponseVO> result = ListObjCopyUtil.copyTo(ls, StrategicPartnersListResponseVO.class);

            	EntityWrapper wrapper = new EntityWrapper();
            	SAttachment param = new SAttachment();
            	for(StrategicPartnersListResponseVO vo : result){
            		param.setRelatedId(vo.getId());
            		param.setAttachmentType(AttachmentTypeEnum.ATTACHMENT_TYPE_35.getCode());
            		param.setAttachmentSubType(AttachmentSubTypeEnum.ATTACHMENTSUBTYPE_2.getCode());
            		param.setDelFlag(CommonConstants.NO_INTEGER);
            		wrapper.setEntity(param);
            		List<SAttachment> attachments = sAttachmentService.selectList(wrapper);
            		List<AttachmentVO> lstAttachments = ListObjCopyUtil.copyTo(attachments, AttachmentVO.class);

            		vo.setLstAttachments(lstAttachments);
            	}

            	pageCode.setList(result);

            }else{
            	pageCode.setList(null);
            }
			LicenseUtil.INSTANCE.validate();

            hResult = new RestReturnResult(CommonConstants.SUCCESS, pageCode);

		}catch(Exception e){
			e.printStackTrace();
			logger.error("==============getStrategicPartnersList=============e:====" + e.getMessage());
			throw new RuntimeException(e.getMessage(), e.getCause());
		}

		return hResult;
	}

}
